package cn.maihe.elg.operation.web.freeLogin;

import cn.maihe.elg.operation.model.dto.BaseResponse;
import cn.maihe.elg.operation.model.enums.*;
import cn.maihe.elg.operation.model.vo.business.BidCustomerBO;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDO;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDOCondition;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.CustomerAttachmentService;
import cn.maihe.elg.operation.service.business.ExchangeCenterService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.utils.CreateGuaranteeUtil;
import cn.maihe.elg.operation.utils.IdGenerate;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;


@Api(value = "免登入", tags = "免登入")
@RestController
@RequestMapping("/api/freeLogin")
@Slf4j
public class FreeLoginController {

    @Autowired
    private BidCustomerService bidCustomerService;
    @Resource
    private CustomerAttachmentService customerAttachmentService;
    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private ExchangeCenterService exchangeCenterService;

    @Value("${cn.maihe.elg.auto-audit-flag:false}")
    private Boolean autoAuditFlag;
    @ApiOperation(value = "免登入", notes = "免登入")
    @RequestMapping(value = "/freeLoginCheck", method = RequestMethod.GET)
    public BaseResponse<String> freeLoginCheck(@RequestParam Long bidCustomerId) {
        if (bidCustomerId != null){
            BidCustomerDO bidCustomerDO = bidCustomerService.selectById(bidCustomerId);
            if (bidCustomerDO == null) {
                log.error("freeLoginCheck centerOrderInfo is null. bidCustomerId={}", bidCustomerId);
                return  BaseResponse.error("查不到客户数据");
            }
            return BaseResponse.success(bidCustomerService.getBidCustomerBO(bidCustomerId, bidCustomerDO));
        }else {
            return BaseResponse.error("客户id为空");
        }
    }
    @ApiOperation(value = "更新客户信息（免鉴权）", notes = "用于投标人完善自己的信息")
    @PostMapping("/updateInfo")
    public BaseResponse<Object> updateInfo(@Validated @RequestBody BidCustomerBO vo) {

        Assert.notNull(vo.getId(), "投标客户主键Id不能为空");
        BidCustomerDO cDO = BidCustomerDO.of(vo);
        cDO.setUserModified(cDO.getBidderCreditCode());
        cDO.setGmtModified(new Date());

        bidCustomerService.checkBidderContractInfo(cDO);

        BidCustomerDO currentCustomerState = bidCustomerService.selectById(vo.getId());
        if (bidCustomerService.isUpdateCompleteFlag(currentCustomerState)) {
            cDO.setCompleteFlag(1);
        }

        List<CustomerAttachmentDO> existingAttachments = customerAttachmentService.selectList(
                CustomerAttachmentDOCondition.builder().andBidderIdEq(vo.getId()).build()
        );
        Set<CustomerAttachmentTypeEnum> typesToProcess = CustomerAttachmentTypeEnum.getAll();

        existingAttachments.forEach(attach -> {
            CustomerAttachmentTypeEnum type = CustomerAttachmentTypeEnum.resolve(attach.getAttachType());
            if (type != null) {
                String newPath = getAttachmentPathByType(vo, type);
                if (newPath != null) {
                    attach.setAttachPath(newPath);
                    attach.setAttachFileName(newPath);
                    typesToProcess.remove(type);
                }
            }
        });

        List<CustomerAttachmentDO> newAttachments = new ArrayList<>();
        typesToProcess.forEach(type -> {
            String path = getAttachmentPathByType(vo, type);
            if (StringUtils.isNotBlank(path)) {
                newAttachments.add(setCustomerAttachment(vo.getId(), type.getType(), path));
            }
        });
        try {
            bidCustomerService.updateByFreeLogin(cDO, existingAttachments, newAttachments);
        } catch (Exception e) {
            log.error("免鉴权更新Service层失败", e);
            return BaseResponse.error(e.getMessage());
        }

        BidCustomerDO updatedBidCustomer = bidCustomerService.selectById(vo.getId());
        if (BidCustomerStatus.NORMAL.getStatus() != updatedBidCustomer.getStatus()) {
            if (autoAuditFlag) {
                bidCustomerService.customerSuccess(updatedBidCustomer);
            } else {
                String acceptOrderNo = vo.getAcceptOrderNo();
                if (StringUtils.isNotBlank(acceptOrderNo)) {
                    AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.getByAcceptOrderNo(acceptOrderNo);
                    if (Objects.nonNull(acceptOrderInfoDO)) {
                        CenterNoEnum centerNoEnum = exchangeCenterService.getCenterNoEnumById(acceptOrderInfoDO.getCenterId());
                        if (CreateGuaranteeUtil.isSuiXing(centerNoEnum, acceptOrderInfoDO.getClientId())) {
                            bidCustomerService.customerSuccess(updatedBidCustomer);
                        }
                    }
                }
            }
        }

        BidCustomerDO finalBidCustomer = bidCustomerService.selectById(vo.getId());
        JSONObject data = new JSONObject();
        data.put("id", finalBidCustomer.getId());
        data.put("status", finalBidCustomer.getStatus());
        return BaseResponse.success(data);
    }

    private CustomerAttachmentDO setCustomerAttachment(Long bidderId, String attachType, String fileName) {
        CustomerAttachmentDO customerAttachmentDO = new CustomerAttachmentDO();
        customerAttachmentDO.setId(IdGenerate.getId());
        customerAttachmentDO.setBidderId(bidderId);
        customerAttachmentDO.setAttachType(attachType);
        customerAttachmentDO.setAttachPath(fileName);
        customerAttachmentDO.setAttachFileName(fileName);
        return customerAttachmentDO;
    }

    private String getAttachmentPathByType(BidCustomerBO vo, CustomerAttachmentTypeEnum type) {
        switch (type) {
            case TYPE_0: return vo.getBusinessLicensePic();
            case TYPE_1: return vo.getAccountOpenLicensePic();
            case TYPE_2: return vo.getLegalIdcardPic();
            case TYPE_3: return vo.getLegalIdcard1Pic();
            case TYPE_4: return vo.getApplyPic();
            case TYPE_5: return vo.getContactPic();
            case TYPE_6: return vo.getAuthPic();
            case TYPE_7: return vo.getQualificationPic();
            default: return null;
        }
    }
    private BidCustomerBO getBidCustomerBO(Long id, BidCustomerDO bidCustomerDO) {
        BidCustomerBO bidCustomerBO = new BidCustomerBO();
        BeanUtils.copyProperties(bidCustomerDO, bidCustomerBO);

        List<CustomerAttachmentDO> customerAttachmentDOS = customerAttachmentService.getAttachmentDO(id, null);

        customerAttachmentDOS.forEach(attach -> {
            CustomerAttachmentTypeEnum type = CustomerAttachmentTypeEnum.resolve(attach.getAttachType());
            switch (type) {
                case TYPE_0:
                    bidCustomerBO.setBusinessLicensePic(attach.getAttachFileName());
                    break;
                case TYPE_1:
                    bidCustomerBO.setAccountOpenLicensePic(attach.getAttachFileName());
                    break;
                case TYPE_2:
                    bidCustomerBO.setLegalIdcardPic(attach.getAttachFileName());
                    break;
                case TYPE_3:
                    bidCustomerBO.setLegalIdcard1Pic(attach.getAttachFileName());
                    break;
                case TYPE_4:
                    bidCustomerBO.setApplyPic(attach.getAttachFileName());
                    break;
                case TYPE_5:
                    bidCustomerBO.setContactPic(attach.getAttachFileName());
                    break;
                case TYPE_6:
                    bidCustomerBO.setAuthPic(attach.getAttachFileName());
                    break;
                case TYPE_7:
                    bidCustomerBO.setQualificationPic(attach.getAttachFileName());
                    break;
            }

        });
        return bidCustomerBO;
    }
//    @ApiOperation(value = "修改投标客户信息", notes = "根据投标客户信息id修改投标客户信息")
//    @RequestMapping(value = "/bidCustomer", method = RequestMethod.PUT)
//    public BaseResponse<Object> modifyBidCustomer(@Validated @RequestBody BidCustomerBO vo) {
//        // 暂无手动创建用户，不创建 valid VO
//        BidCustomerDO cDO = BidCustomerDO.of(vo);
//        Assert.notNull(vo.getId(), "投标客户主键Id不能为空");
//        bidCustomerService.checkBidderContractInfo(cDO);
//        cDO.setUserModified(UserContextUtil.getUserContext().getUsername());
//        cDO.setGmtModified(new Date());
//
//        /*
//          根据客户id获取客户信息，判断审核状态status是否为1补全状态字段completeflag是否为0 修改补全状态字段为1
//        */
//        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(vo.getId());
//        if (bidCustomerService.isUpdateCompleteFlag(bidCustomerDO)){
//            cDO.setCompleteFlag(1);
//        }
//
//        List<CustomerAttachmentDO> customerAttachmentDOS = customerAttachmentService.selectList(
//                CustomerAttachmentDOCondition.builder().andBidderIdEq(vo.getId()).build()
//        );
//        Set<CustomerAttachmentTypeEnum> set = CustomerAttachmentTypeEnum.getAll();
//        customerAttachmentDOS.forEach(attach -> {
//            CustomerAttachmentTypeEnum type = CustomerAttachmentTypeEnum.resolve(attach.getAttachType());
//            switch (type) {
//                case TYPE_0:
//                    attach.setAttachPath(vo.getBusinessLicensePic());
//                    attach.setAttachFileName(vo.getBusinessLicensePic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_0);
//                    break;
//                case TYPE_1:
//                    attach.setAttachPath(vo.getAccountOpenLicensePic());
//                    attach.setAttachFileName(vo.getAccountOpenLicensePic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_1);
//                    break;
//                case TYPE_2:
//                    attach.setAttachPath(vo.getLegalIdcardPic());
//                    attach.setAttachFileName(vo.getLegalIdcardPic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_2);
//                    break;
//                case TYPE_3:
//                    attach.setAttachPath(vo.getLegalIdcard1Pic());
//                    attach.setAttachFileName(vo.getLegalIdcard1Pic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_3);
//                    break;
//                case TYPE_4:
//                    attach.setAttachPath(vo.getApplyPic());
//                    attach.setAttachFileName(vo.getApplyPic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_4);
//                    break;
//                case TYPE_5:
//                    attach.setAttachPath(vo.getContactPic());
//                    attach.setAttachFileName(vo.getContactPic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_5);
//                    break;
//                case TYPE_6:
//                    attach.setAttachPath(vo.getAuthPic());
//                    attach.setAttachFileName(vo.getAuthPic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_6);
//                    break;
//                case TYPE_7:
//                    attach.setAttachPath(vo.getQualificationPic());
//                    attach.setAttachFileName(vo.getQualificationPic());
//                    set.remove(CustomerAttachmentTypeEnum.TYPE_7);
//                    break;
//            }
//        });
//        List<CustomerAttachmentDO> customerAttachmentDOS1 = new ArrayList<>();
//        set.forEach(type -> {
//            switch (type) {
//                case TYPE_0:
//                    CustomerAttachmentDO businessLicenseAttach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_0.getType(), vo.getBusinessLicensePic());
//                    customerAttachmentDOS1.add(businessLicenseAttach);
//                    break;
//                case TYPE_1:
//                    CustomerAttachmentDO accountOpenLicenseAttach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_1.getType(), vo.getAccountOpenLicensePic());
//                    customerAttachmentDOS1.add(accountOpenLicenseAttach);
//                    break;
//                case TYPE_2:
//                    CustomerAttachmentDO legalIdcardAttach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_2.getType(), vo.getLegalIdcardPic());
//                    customerAttachmentDOS1.add(legalIdcardAttach);
//                    break;
//                case TYPE_3:
//                    CustomerAttachmentDO legalIdcard1Attach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_3.getType(), vo.getLegalIdcard1Pic());
//                    customerAttachmentDOS1.add(legalIdcard1Attach);
//                    break;
//                case TYPE_4:
//                    CustomerAttachmentDO ApplyAttach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_4.getType(), vo.getApplyPic());
//                    customerAttachmentDOS1.add(ApplyAttach);
//                    break;
//                case TYPE_5:
//                    CustomerAttachmentDO contactAttach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_5.getType(), vo.getContactPic());
//                    customerAttachmentDOS1.add(contactAttach);
//                    break;
//                case TYPE_6:
//                    CustomerAttachmentDO authAttach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_6.getType(), vo.getAuthPic());
//                    customerAttachmentDOS1.add(authAttach);
//                    break;
//                case TYPE_7:
//                    CustomerAttachmentDO qualificationAttach = setCustomerAttachment(
//                            vo.getId(), CustomerAttachmentTypeEnum.TYPE_7.getType(), vo.getQualificationPic());
//                    customerAttachmentDOS1.add(qualificationAttach);
//                    break;
//            }
//        });
//
//        bidCustomerService.update(cDO, customerAttachmentDOS, customerAttachmentDOS1);
//
//        if (UserContextUtil.getUserContext().getUserType() != UserType.BIDDER.getType()) {
//            BidderLevel bidderLevel = BidderLevel.resolve(cDO.getBidderLevel());
//            //资质级别不为空则开始计算更新已入库未计算保费的订单
//            if (bidderLevel != null) {
//                //更新未审核通过之前且已提交订单未计算手续费订单
//                acceptOrderInfoService.updateUnFeeAcceptOrderInfo(cDO);
//            }
//
//        }
//
//        BidCustomerDO bidCustomer = bidCustomerService.selectById(vo.getId());
//        if (UserContextUtil.getUserContext().getUserType() == UserType.BIDDER.getType()) {
//            if (BidCustomerStatus.NORMAL.getStatus() != bidCustomer.getStatus()) {
//                if (autoAuditFlag){
//                    // 客户信息自动审核通过
//                    bidCustomerService.customerSuccess(bidCustomer);
//                }else{
//                    String acceptOrderNo = vo.getAcceptOrderNo();
//                    if(StringUtils.isNotBlank(acceptOrderNo)){
//                        AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.getByAcceptOrderNo(acceptOrderNo);
//                        if(Objects.nonNull(acceptOrderInfoDO)){
//                            CenterNoEnum centerNoEnum = exchangeCenterService.getCenterNoEnumById(acceptOrderInfoDO.getCenterId());
//                            if(CreateGuaranteeUtil.isSuiXing(centerNoEnum,acceptOrderInfoDO.getClientId())){
//                                // 客户信息自动审核通过
//                                bidCustomerService.customerSuccess(bidCustomer);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//
//        JSONObject data = new JSONObject();
//        data.put("id",bidCustomer.getId());
//        data.put("status",bidCustomer.getStatus());
//        return BaseResponse.success(data);
//    }
//    private CustomerAttachmentDO setCustomerAttachment(Long bidderId, String attachType, String fileName) {
//        CustomerAttachmentDO customerAttachmentDO = new CustomerAttachmentDO();
//        customerAttachmentDO.setId(IdGenerate.getId());
//        customerAttachmentDO.setBidderId(bidderId);
//        customerAttachmentDO.setAttachType(attachType);
//        customerAttachmentDO.setAttachPath(fileName);
//        customerAttachmentDO.setAttachFileName(fileName);
//        return customerAttachmentDO;
//    }
}
